package com.atom.module.lib.opengles.egl

import android.opengl.*

data class EGLWrapper(
    val key: Int,
    val major: Int,
    val minor: Int,
    var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
) {
    enum class SurfaceType {
        Window, Offscreen, NONE
    }

    var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
    var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE
    var eglSurfaceType: SurfaceType = SurfaceType.NONE
    var eglConfig: EGLConfig? = null

    fun setSurface(surface: EGLSurface, type: SurfaceType) {
        this.eglSurface = surface
        this.eglSurfaceType = type
    }

    fun reset() {
        eglDisplay = EGL14.EGL_NO_DISPLAY
        eglContext = EGL14.EGL_NO_CONTEXT
        eglSurface = EGL14.EGL_NO_SURFACE
        eglConfig = null
    }

    fun release() {
        EGLHelper.destroy(this)
        reset()
    }

    /**
     * 创建 EGL config context surface
     */
    fun createGLESWithSurface(
        attrs: EGLConfigAttrs = EGLConfigAttrs().version(3).recordableType(true),
        ctxAttrs: EGLContextAttrs = EGLContextAttrs().version(3),
        surface: Any
    ): Boolean {
        return EGLHelper.createGLESWithSurface(this, attrs, ctxAttrs, surface)
    }

    /**
     * 创建一个后台EGL surface
     * 和 window surface 的不同的是, 该surface 可以配置其宽高
     */
    fun createGLESWithPBuffer(
        attrs: EGLConfigAttrs = EGLConfigAttrs().version(3).recordableType(true),
        ctxAttrs: EGLContextAttrs = EGLContextAttrs().version(3),
        width: Int,
        height: Int
    ): Boolean {
        return EGLHelper.createGLESWithPBuffer(this, attrs, ctxAttrs, width, height)
    }


    fun getSurface(): EGLSurfaceWrapper {
        return EGLSurfaceWrapper(this)
    }

    fun isCurrent(): Boolean {
        return EGLHelper.isSurfaceCurrent(this)
    }

    fun makeCurrent() {
        EGLHelper.makeCurrent(this)
    }

    fun makeNothingCurrent() {
        EGLHelper.makeNothingCurrent(this)
    }

    fun setPresentationTime(nsecs: Long) {
        EGLHelper.setPresentationTime(this, nsecs)
    }

    fun swapBuffers(): Boolean {
        return EGLHelper.swapBuffers(this)
    }

    override fun toString(): String {
        return "EGLWrapper(key=$key, major=$major, minor=$minor, eglDisplay=$eglDisplay, eglContext=$eglContext, eglSurface=$eglSurface, eglConfig=$eglConfig)"
    }
}
